package com.elysia.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 过滤器，用于屏蔽登陆前的操作
 */
@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //需要从 `session` 对象中获取用户信息，但是 `ServletRequest`
        // 类型的 requset 对象没有获取 session 对象的方法，所以此时需要将 request对象强转成 `HttpServletRequest` 对象。
        HttpServletRequest req = (HttpServletRequest) servletRequest;

        //判断访问资源路径是否和登录注册相关
        //1,在数组中存储登陆和注册相关的资源路径
        String[] urls = {"/login.jsp","/imgs/","/css/","/loginServlet","/register.jsp",
                "/registerServlet","/checkCodeServlet"};

        //2.遍历数组，获取到每一个需要执行的资源路径
        String url = req.getRequestURL().toString();

        //4,判断当前访问的资源路径字符串是否包含要放行的的资源路径字符串
            /*
                比如当前访问的资源路径是  /brand-demo/login.jsp
                而字符串 /brand-demo/login.jsp 包含了  字符串 /login.jsp ，所以这个字符串就需要放行
            */
        for (String u : urls) {
            if (url.contains(u)){
                //找到了，放行
                filterChain.doFilter(servletRequest,servletResponse);
                return;
            }
        }


        //1.获取Session对象，获取名为 user 的数据
        HttpSession session = req.getSession();
        Object user = session.getAttribute("user");

        //2.判断 user 是否为null
        if (user != null){
            //user不为null就说明已经登陆了
            //放行
            filterChain.doFilter(servletRequest,servletResponse);
        } else {
            //user为空说明还没有登陆，跳转回login.jsp
            req.setAttribute("login_msg","您还尚未登陆");
            req.getRequestDispatcher("/login.jsp").forward(req,servletResponse);
        }

    }

    @Override
    public void destroy() {

    }
}
